package com.eportal.action.background;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TKeys;
import com.eportal.domain.TKeysProlong;
import com.eportal.domain.TLock;
import com.eportal.domain.TUsers;
import com.eportal.service.TKeysProlongService;
import com.eportal.service.TKeysService;
import com.eportal.service.TLocksService;
import com.eportal.service.TUsersService;
import com.eportal.util.DateUtils;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 钥匙管理
 * @author chencheng
 *
 */
public class TKeysAction extends BaseAction implements ModelDriven<TKeys> {

    /**
	 * @author chencheng
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TKeysAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();
    
    @Autowired
    private TKeysService tKeysService;
    @Autowired
    private TUsersService tUsersService;
    @Autowired
    private TLocksService tlocksService;
    @Autowired
    private TKeysProlongService tKeysProlongService;
	/**
     * 钥匙管理
     */
    public String listView() {
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("rLevel", user.getrLevel());
        return SUCCESS;
    }
    
    /**
     * 钥匙列表
     */
    public void page() throws Exception {
    	 JqGridPager jqGridPager = new JqGridPager();
     	String agtCode = getRequest().getParameter("agtCode");
     	String communityId = getRequest().getParameter("communityId");
     	String cityCode = getRequest().getParameter("cityCode");
     	
     	String reqtime = getRequest().getParameter("reqtime");
     	String validity = getRequest().getParameter("validity");
     	String pid = getRequest().getParameter("pid");
     	
     	String userName = getRequest().getParameter("userName");
     	String cbName = getRequest().getParameter("cbName");
     	String tel = getRequest().getParameter("tel");
     	
     	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (!StringUtils.isBlank(agtCode)) {
                where.append(" and ab.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
        	if (!StringUtils.isBlank(communityId)) {
        		where.append(" and ab.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
        	if (userRole == 21) {
    			where.append(" and ab.sysoptId =");
    			where.append(user.getSid());
			}
		}else	if (userRole == 3 || userRole == 4) {
			where.append(" and ab.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			if (!StringUtils.isBlank(communityId)) {
        		where.append(" and ab.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and ab.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    		if (user.getrLevel()==4) {
    			where.append(" and ab.status !=2 ");
			}
    	}
    	
     	if (StringUtils.isNotBlank(cityCode)) {
     		where.append(" and ab.cityCode like'%");
     		where.append(cityCode);
     		where.append("%'");
     	}
     	if (!StringUtils.isBlank(reqtime)) {
     		where.append(" and TO_CHAR (ab.req_time,'YYYY-MM-DD') ='");
     		where.append(reqtime);
     		where.append("'");
     	}
     	if (!StringUtils.isBlank(validity)) {
     		where.append(" and TO_CHAR (ab.validity,'YYYY-MM-DD') ='");
     		where.append(validity);
     		where.append("'");
     	}
     	if (StringUtils.isNotBlank(userName)) {
     		where.append(" and ab.auname like'%");
     		where.append(userName);
     		where.append("%'");
     	}
     	
     	if (StringUtils.isNotBlank(cbName)) {
     		where.append(" and ab.lock_name like'%");
     		where.append(cbName);
     		where.append("%'");
     	}
     	if (StringUtils.isNotBlank(tel)) {
     		where.append(" and ab.tel='");
     		where.append(tel);
     		where.append("'");
     	}
     	if (StringUtils.isNotBlank(pid)) {
     		where.append(" and ab.pid='");
     		where.append(pid);
     		where.append("'");
     	}
     	jqGridPager.setWhere(where.toString());
         setPage(getRequest(), jqGridPager);
         String sql = "select ab.* from("
 		 		+ "select t.sid,t.pid,t.communityid,t.lock_name,t.status,t.req_time,TO_CHAR (t.req_time,'yyyy-MM-dd HH24:mi:ss') as reqtime,t.validity,TO_CHAR (t.validity,'yyyy-MM-dd') as validity1,a.agtcode,a.agtname,a.sysoptId,c.communityname,c.citycode,u.tel,u.auname,"
				+ "(select min(t1.utype) from t035_room_user t1 where t1.app_userid = t.userid and t1.room_id in (select t2.sid from t035_room t2 where t2.unit_id=t.installunitid)) utype,u.userid " 		 		
 		 		+ "from T06_KEYS t "
 		 		+ "left join t03_community c on t.communityid=c.sid "
 		 		+ "left join t02_agtent a on c.agtcode=a.agtcode "
 		 		+ "left join t04_users u on t.userid=u.userid "
 		 		+ ") ab";
         List<Map<String, Object>> tKeysList = tKeysService.list(sql,jqGridPager);
         for(Map map:tKeysList){
        	Timestamp t = (Timestamp)map.get("validity");
        	if(t.getTime()<System.currentTimeMillis()){
        		map.put("STATUS_", "-1000");//钥匙过期
        	}else{
        		map.put("STATUS_", map.get("status"));
        	}
         }
        jqGridQueryMap(TKeys.class, getRequest(), tKeysList, getResponse(), jqGridPager);
    }
    
    /**
     * APP端——智能锁详情列表
     */
    public String listViewApp() {
    	int countSize = tKeysService.countSizeApp(getPageAppWhere());
    	if (countSize != 0) {
    		countSize = countSize/10 +1;
		}
    	getRequest().setAttribute("show",getRequest().getParameter("show"));
    	getRequest().setAttribute("countSize",countSize);
    	return SUCCESS;
    }
    
    
    /**
     * 钥匙列表
     */
    public void pageApp() throws Exception {
    	String page = getRequest().getParameter("page");
    	String size = getRequest().getParameter("size");
    	String type = getRequest().getParameter("type");
    	if (StringUtils.isBlank(size) || StringUtils.isBlank(page)) {
			return;
		}
    	int pageNum = Integer.parseInt(page);
    	int sizeNum = Integer.parseInt(size);
    	int beginNum = pageNum * sizeNum;
    	int endNum = (pageNum+1) * sizeNum;
    	String where  = getPageAppWhere();
    	
    	List<Map<String, Object>> tKeysList = tKeysService.listPageApp(where,beginNum,endNum,type);
    	responseBody(tKeysList);
    }
    
    private String getPageAppWhere() {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (userRole == 3 || userRole == 4) {
			where.append(" and c.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    		where.append(" and t.status !=2 ");
    	}
    	return where.toString();
	}

	/**
     * 钥匙增加
     */
    public String addView() {
        return SUCCESS;
    }
    
    /**
     * 钥匙新增保存
     */
    public void add(){
    	TKeys tKeys = getModel();
    	result = tKeysService.addMethod(tKeys);
        responseBody(result);
    }
    
    
    /**
     * 手机移动端发钥匙
     */
    public String sendView4App(){
    	try{
    		Sysopt opt = (Sysopt)getRequest().getSession().getAttribute("user");
        	List list = tlocksService.getBySql("and communityid='"+opt.getCommunityId()+"'");
        	getRequest().setAttribute("datalist", list);
        	
        	String prolong = getRequest().getParameter("prolong");
        	if("1".equals(prolong)){//延期钥匙
        		String prolongId = getRequest().getParameter("prolongId");	
        		TKeysProlong bean = tKeysProlongService.get(Long.valueOf(prolongId));
        		if(bean!=null){
        			TLock lock =  tlocksService.getByPid(tKeysService.get(Long.valueOf(bean.getKsid())).getPid());
        			TUsers users = tUsersService.getByUserid(bean.getApplyUserid());
        			getRequest().setAttribute("auname",users.getAuName());
        			getRequest().setAttribute("lockid",lock.getSid());
        			getRequest().setAttribute("tel",users.getTel());
        			getRequest().setAttribute("prolong",prolong);
        			getRequest().setAttribute("prolongId",prolongId);
        			getRequest().setAttribute("lockName",lock.getInstallLockName());
        		}
        	}
    	}catch(Exception e){
    		log.error(this,e);
    		return "error";
    	}
    	
    	return SUCCESS;
    }
    
    
    /**
     * 钥匙修改
     */
    public String editView() {
    	TKeys tKeys = tKeysService.get(getModel().getSid());
        getRequest().setAttribute("tKeys", tKeys);
        return SUCCESS;
    }
    
    /**
     * 钥匙修改保存
     */
    public void update(){
    	TKeys tKeys = getModel();
    	result = tKeysService.updateMethod(tKeys);
        responseBody(result);
    }
    
    
    /**
     * 删除
     */
    public void delete(){
    	String param_ids = getRequest().getParameter("ids");
    	result = tKeysService.deleteMethod(param_ids);
        responseBody(result);
    }
    
    /**
     * 用户钥匙详情
     * @throws Exception
     */
    public void keysDetailQuery() throws Exception {
    	 JqGridPager jqGridPager = new JqGridPager();
    	 List<Map<String, Object>> tKeysList = new ArrayList<Map<String,Object>>();
    	 String userId = getRequest().getParameter("userId");
    	 if (!tUsersService.haveRole(userId)) {
    		 jqGridQueryMap(TKeys.class, getRequest(), tKeysList, getResponse(), jqGridPager);
    		 return;
 		 }
    	 int userRole =  (Integer) getSession().getAttribute("userRole");
 		 Sysopt  user= (Sysopt)getSession().getAttribute("user");
         setPage(getRequest(), jqGridPager);
         StringBuffer sql  = new StringBuffer("");
         sql.append("select t.sid,t.pid,t.status,t.lock_name,t.req_time,t.validity,TO_CHAR (t.validity,'yyyy-MM-dd') as validity1,t.userid,nvl(o.openNum,0) as openNum,nvl(m.sharenum,0) as shareNum from T06_KEYS t "
         		+ "INNER JOIN (select t.pid,max(t.req_time) as  reqTime  from  T06_KEYS t where t.userId= '");
         sql.append(userId);
         sql.append("' group by pid) b ");
         sql.append("on t.pid=b.pid and t.req_time=b.reqTime ");
         sql.append("left join (select count(sid) as openNum,o.pid,o.auid  from topenlog o where o.ktype='0' and o.auid= '");
         sql.append(userId);
         sql.append("' group by o.pid,o.auid ) o on t.pid = o.pid ");
         sql.append("left join (select  count(m.sid)as sharenum,m.puid,m.pid  from tmirror_keys m where m.puid='");
         sql.append(userId);
         sql.append("'  group by m.puid,m.pid )m on t.pid=m.pid ");
         if (userRole == 3 || userRole == 4) {
        	 sql.append("left join t04_users u on t.userid= u.userid ");
      	 }
         sql.append(" where t.userId= '");
         sql.append(userId);
         sql.append("'");
         if (userRole == 3 || userRole == 4) {
        	 sql.append(" and u.agtcode='");
        	 sql.append(user.getAgtCode());
        	 sql.append("'");
      	 }
         if (userRole == 5 || userRole == 6) {
        	 sql.append(" and t.communityId='");
        	 sql.append(user.getCommunityId());
        	 sql.append("'");
        	 if ("4".equals(user.getrLevel())) {
        		 sql.append(" and t.status !=2 ");
 			}
      	 }
         tKeysList = tKeysService.list(sql.toString(),jqGridPager);
         jqGridQueryMap(TKeys.class, getRequest(), tKeysList, getResponse(), jqGridPager);
    }
    
    /**
     * 钥匙修改日期
     */
    public String changeKeysValidity() {
    	String sid = getRequest().getParameter("sid");
    	String validity = getRequest().getParameter("validity");
    	getRequest().setAttribute("sid", sid);
    	getRequest().setAttribute("validity", validity);
        return SUCCESS;
    }
    
    /**
     * 钥匙修改日期
     */
    public String selectKeysValidity() {
    	return SUCCESS;
    }
    
    /**
     * 用户钥匙修改操作
     */
    public void changeKeys(){
    	 try {
	    	String sid = getRequest().getParameter("sid");
	    	String status = getRequest().getParameter("status");
	    	String validity = getRequest().getParameter("validity");
	    	String startTime = getRequest().getParameter("startTime");
	    	String[] sids = sid.split(",");
	    	for(String id:sids){
		    	TKeys tKeys = tKeysService.get(Long.parseLong(id));
		    	 String where ="userId= '"+tKeys.getUserId()+"'";
		    	 TUsers tUser = tUsersService.getByWhere(where);
		    	result = tKeysService.changeKeysStatusMethod(id,status,validity,tUser);	    		
	    	}
    	 } catch (Exception e) {
             log.error("钥匙状态修改异常", e);
             result.put("code", 0);
             result.put("msg", "钥匙状态修改异常");
         }
        responseBody(result);
    }
    
    
    /**
     * 修改钥匙有效期，目前供app调用
     */
	public void changeKeyV2() {
		try {
			String sid = getRequest().getParameter("sid");
			String status = getRequest().getParameter("status");
			String endTime = getRequest().getParameter("endTime_");
			String startTime = getRequest().getParameter("startTime_");
			String[] sids = sid.split(",");
			for (String id : sids) {
				TKeys tKeys = tKeysService.get(Long.parseLong(id));
		    	TUsers tUser = tUsersService.getByUserid(tKeys.getUserId());
		    	Date endTime_ = new Date(Long.valueOf(endTime));
		    	Date startTime_ = new Date(Long.valueOf(startTime));
		    	
		    	
				result = tKeysService.syncTo(tUser.getUserId(), tUser.getTel(), tKeys.getPid(), endTime_,tUser.getAgtCode(), endTime_, startTime_);
			}
		} catch (Exception e) {
			log.error("钥匙状态修改异常", e);
			result.put("code", 0);
			result.put("msg", "钥匙状态修改异常");
		}
		responseBody(result);
	}
    
    /**
     * 钥匙分享记录
     */
    public String shareKeysView() {
    	String userId = getRequest().getParameter("userId");
    	String pid = getRequest().getParameter("pid");
    	getRequest().setAttribute("userId", userId);
    	getRequest().setAttribute("pid", pid);
    	return SUCCESS;
    }
    
    /**
     * 用户钥匙详情
     * @throws Exception
     */
    public void shareKeys() throws Exception {
    	 JqGridPager jqGridPager = new JqGridPager();
    	 List<Map<String, Object>> tKeysList = new ArrayList<Map<String,Object>>();
    	 String userId = getRequest().getParameter("userId");
    	 String pid = getRequest().getParameter("pid");
         setPage(getRequest(), jqGridPager);
         StringBuffer sql  = new StringBuffer("");
         sql.append("select t.puid,t.pid,to_char(t.expiretime,'yyyy-MM-dd HH24:mi:ss') as expiretime,to_char(t.createtime,'yyyy-MM-dd HH24:mi:ss') as createtime,to_char(t.bindmirrorusertime,'yyyy-MM-dd HH24:mi:ss') as bindmirrorusertime,l.install_lock_name as lockName "
         		+ "from TMIRROR_KEYS t "
         		+ "left join t05_locks l on t.pid=l.pid "
         		+ "where t.puid='");
         sql.append(userId);
         sql.append("' and t.pid='");
         sql.append(pid);
         sql.append("'");
         tKeysList = tKeysService.list(sql.toString(),jqGridPager);
         jqGridQueryMap(TKeys.class, getRequest(), tKeysList, getResponse(), jqGridPager);
    }
    
    /**
     * 
     * 审批钥匙延期的列表
     * 
     * @throws Exception
     */
    public void page4Prolong() throws Exception {
    	try{
    		JqGridPager jqGridPager = new JqGridPager();
        	Sysopt  user= (Sysopt)getSession().getAttribute("user");
        	String next_sid = getRequest().getParameter("next_sid");
        	List<Map<String,Object>> list = tKeysService.page4Prolong(user.getAgtCode(),user.getCommunityId(),next_sid);	
        	for(Map m:list){
        		m.put("TIME_", DateUtils.formatDate((Date)m.get("CTIME")));
        	}
        	
        	 result.put("code", "1");
             result.put("msg", "成功");
             result.put("data", list);
    	}catch(Exception e){
    		log.error(this,e);
    		 result.put("code", 0);
             result.put("msg", "获取数据失败");
    	}
    	responseBody(result);
    }
    
    private TKeys tKeys = new TKeys();

    @Override
    public TKeys getModel() {
        return tKeys;
    }
}
